<template>
    <div>
        <div class="operatBtnWrapper">
            <!-- <button class="operatBtn marR5" @click.stop="">导出权限</button> -->
            <button class="operatBtn marR5" @click.stop="changeUserMenu" v-if="staffNum != 'A99999'">确认修改</button>
            <!-- <button class="operatBtn marR5" @click.stop="resetUserMenu" v-if="staffNum != 'A99999'">重置权限</button> -->
            <!-- <button class="operatBtn marR5" @click.stop="returnBack">返回上一页</button> -->
            <!-- <el-select v-model="selUserId" @change="copyMenuPower" placeholder="请选择要拷贝的人员权限" class="inputTxtWrapper marR5" v-if="staffNum != 'A99999'">
                <el-option
                    v-for="item of userList"
                    :key="item.id"
                    :label="item.user_name"
                    :value="item.id">
                </el-option>
            </el-select> -->
		</div>
        <div class="grayLine marLR20"></div>

        <div class="marLR20">
            <p class="paddT20 font14">姓名：{{userName}}</p>
            <p class="paddBT20 font14">工号：{{staffNum}}</p>
            <div class="marBT20 titleBar">研发管理系统权限(点击人员名字可进行权限拷贝)</div>

            <div>
                <el-table :data="formatData" :row-style="showRow" v-bind="$attrs" 
                                @header-click="copyMenuPower" border="true" class="tableWrapper">
                    <el-table-column width="60" align="center" v-if="columns.length !== 0" :fixed="true" :resizable="false" >
                        <template slot-scope="scope">
                                <el-checkbox v-model="scope.row[columns[0].haspower]" @change="selMenu(scope.row[columns[0].haspower],scope.row,scope.$index)" :disabled = "staffNum === 'A99999'"></el-checkbox>
                        </template>
                    </el-table-column>  
                    <!-- 权限菜单 -->
                    <!-- <el-table-column v-for="(columnMenu, index) in columnMenu" :key="columnMenu.text" :label="columnMenu.text" :width="columnMenu.width">
                        <template slot-scope="scope">
                            <span v-if="index === 0" v-for="space in scope.row._level" class="ms-tree-space" :key="space"></span>
                            <span class="tree-ctrl" v-if="iconShow(index,scope.row)" @click="toggleExpanded(scope.$index)">
                            <i v-if="!scope.row._expanded" class="el-icon-plus"></i>
                            <i v-else class="el-icon-minus"></i>
                            </span>
                            {{scope.row[columnMenu.value]}}
                        </template>
                    </el-table-column> -->
                     <!-- 公司人员 -->
                    <!-- <el-table-column v-for="(column, index) in columns" :key="column.text" :label="column.text" :width="column.width" :fixed="column.text === '权限菜单' || column.text === userName" :index="column.index" align="center"> -->
                    <el-table-column v-for="(column, index) in columns" 
                                                :key="column.text" 
                                                :label="column.text"                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    
                                                :width="column.width" 
                                                :fixed="column.text === '权限菜单(+ / -)' || column.text === userName" 
                                                :index="column.index" 
                                                :resizable="false" 
                                                :align="column.text === '权限菜单(+ / -)' ? 'left' : 'center'"
                                                :type="expand">
                        <template slot-scope="scope">
                            <!-- <span v-if="index === 0" v-for="space in scope.row._level" class="ms-tree-space" :key="space"></span> -->
                            <template v-if="index === 0">
                                <span v-for="space in scope.row._level" class="ms-tree-space" :key="space"></span>
                            </template>
                            <span class="tree-ctrl" v-if="iconShow(index,scope.row)" @click="toggleExpanded(scope.$index)">
                                <i v-if="!scope.row._expanded" class="el-icon-plus"></i>
                                <i v-else class="el-icon-minus"></i>
                            </span>
                            <!-- <span v-if="column.value === '✕'"></span> -->
                            <span :class="{orangeColor:scope.row[column.value] === '√',lightGrayColor:scope.row[column.value] === '✕'}">{{scope.row[column.value]}}</span>
                        </template>
                    </el-table-column>

                    <!-- 公司人员 -->
                    <!-- <el-table-column>
                        <template slot="header" slot-scope="scope">
                            <el-select @change="copyMenuPower" placeholder="请选择要拷贝的人员权限" class="inputTxtWrapper" v-if="staffNum != 'A99999'">
                                <el-option
                                    v-for="item of userList"
                                    :key="item.id"
                                    :label="item.user_name"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                        </template>
                    </el-table-column> -->
                    <slot></slot>
            </el-table>
            </div>
        </div>

        

    </div>
</template>

<script>
import http from '@/assets/js/http'
import _g from '@/assets/js/global'
import treeToArray from '@/assets/js/eval'
 import { mapGetters } from 'vuex'

import treeTable from '@/components/Common/TreeTable'


export default {
    components: { treeTable },
    data(){
        return{
        
        /* 表头 */
        columns: [],
        // columnMenu:[
        //     {
        //         text: '权限菜单',
        //         value: 'menu_name',
        //         haspower:'haspower',
        //         width: 200
        //     }
        // ],
           
           isChange:false,                                          //  默认没有修改权限

            userId:'',                                                              //..用户id
            userName:'',                                                //..姓名
            staffNum:'',                                                     //..工号

            powerList: [],                                          //  权限菜单列表

            rawData:null,                                             //  原始权限菜单列表，初次从服务器加载的数据
            changeData:[],                                      //  变化中的权限菜单列表，主要是为了拷贝权限
            
            userList:[],                                                //  所有用户
            // menuIds:[],                          //  勾选的菜单
            allUserIds:[],                              //  人员id集合

            isMenuExpand:false,                         //  菜单默认收缩

            oldExpandStatusArr:[],                      //  每次拷贝权限，都需要保留上一次菜单的展开状态，key = menu + 菜单id，value = _expanded,_expanded = true代表展开，为false或undefined(初始)代表收缩
            
            defaultProps: {
                children: 'children',
                label: 'menu_name'
            },

        }
    },
    computed: {
    // 格式化数据源 tree-grid
    formatData: function() {
      let tmp
      let data
      let len
      let  oldExpandStatusArr = this.oldExpandStatusArr                                      // 上一次菜单的展开状态
      if (!Array.isArray(this.powerList)) {
        tmp = [this.powerList]
      } else {
        tmp = this.powerList
      }
      const func = treeToArray
      const args = Array.concat([tmp]) 
      
      data = func.apply(null, args)
      len = data.length
    //   主要是为了切换为原来的展开状态
      for(let i = 0;i < len;i++){                                                              
          data[i]._expanded = oldExpandStatusArr[i]
      }
       
      return data
    }
  },
    methods: {
        /* 根据菜单id，返回菜单索引 */
        getArrIndex(arr, id) {
            let index = null;
            arr.every(function(value, i) {
                if (value.id === id) {
                    index = i;
                    return false;
                }
                return true;
            });
            return index;
        },

        /* 深度递归父菜单下的子菜单，返回以竖线分割的菜单id集合字符串 */
        setChildMenuMsg(currMenu){
            if(currMenu.children === undefined){
                return ''
            }else{
                let childMenuIdsStr = ''
                for(let i = 0;i < currMenu.children.length;i++){
                    childMenuIdsStr = childMenuIdsStr + currMenu.children[i].id + '|'
                    childMenuIdsStr = childMenuIdsStr + this.setChildMenuMsg(currMenu.children[i])
                }
                return childMenuIdsStr
            }
        },
        /* 递归某个父菜单下的子菜单，找出至少一个是否有选中的菜单 */
        recurchildMenu(children){
            let isChcked = false                                            //  默认没有子菜单选中
            for(let item of children){
                 if(item.haspower || item.children === undefined ){
                     isChcked = true
                     return isChcked                                                       //  跳出多层for循环
                 }else{
                         this.recurchildMenu(item.children)
                 }   
            }
            return isChcked
        },

        /* 递归父级菜单 */
        recurParentMenu(formData,index,cBool,pBool){
            formData[index].haspower = cBool
            if(formData[index].parent_id === 0){                                       //  如果为一级菜单
                return formData
            }else{
                index = this.getArrIndex(formData,formData[index].parent_id)

                this.recurParentMenu(formData,index,pBool,pBool)
            }
        },
        /* 点击复选框，构造选中的菜单id数组 */
        selMenu(isChecked,row,index){
            let formData = this.formatData

            let cBool = false                                   //  当前菜单默认不选中                                            
            let pBool = false                                   //  当前菜单的所有父菜单默认不选中           
            
            let childMenuIdsStr = ''                        //..子菜单菜单id集合字符串
            let childMenuIdsArr = []                     //..子菜单菜单id集合数组

            this.isChange = true

            cBool = isChecked > 0 ? true : false　                                      //  当前菜单选中与否

            if(row.children !== undefined && !cBool){               //  如果当前菜单不选中，且当前菜单含有子菜单，则设置下属子菜单全部不选中
                childMenuIdsStr = this.setChildMenuMsg(formData[index])
                childMenuIdsArr = childMenuIdsStr.split('|')
                childMenuIdsArr.pop()                      //..删除最后一个空字符串元素，因为|分割的缘故 
               
                //   设置当前菜单及子菜单为不选中
                for(let item of formData){
                    for(let childMenuId of childMenuIdsArr){
                        if(item.id === parseInt(childMenuId)){
                            item.haspower = false                                       //  设置为不选中
                        }
                    }
                } 
            }
            if(cBool){
                 if(row.parent_id !== 0){                                                            //  如果当前菜单含有祖先菜单
                let chilren = row.parent.children                                           //  获取子菜单
                    pBool = this.recurchildMenu(chilren)                         
                }
                this.recurParentMenu(formData,index,cBool,pBool)   
            }

            this.formatData = [].concat(formData)
         
        },
         /* 返回上一页  */
        // returnBack(){
        //     this.$router.push('/admin/users/list')
        // },
        /* 根据表格显示规则，格式化数据 */
        formatDataByTableRule(){
            const that = this
            let tmpList = that.changeData

             let columns = []
             let column = {}   
             
             let tmpMenuList = []
             let powerList = []                                                                 //  当前用户权限菜单


            // 找出当前用户信息
            for(let i = 0;i < tmpList.length;i++){
                column = {
                    id:'id',                                                                                                 //  菜单id
                    index:i,                                                                                                //  人员索引
                    userId:tmpList[i].userId,
                    text : tmpList[i].user_name,
                    value : 'txt' + tmpList[i].userId,
                    haspower : 'haspower',
                }

                if(tmpList[i].userId == that.userId){                                                  //  如果找到当前用户

                    if(!that.rawData){                                                          //  如果为空，则存储当前人员(第一次初始)
                        that.rawData = {
                            menu :  [].concat(tmpList[i].menu),
                            menuIds :  [].concat(tmpList[i].menuIds),
                            userId :  that.userId,
                        }
                    }

                    columns.unshift(column)
                    that.powerList = [].concat(tmpList[i].menu)
                    // that.menuIds = [].concat(tmpList[i].menuIds )                                              //  权限数字数组

                }else{
                    columns.push(column)
                        // tmpMenuList = [].concat(tmpMenuList,tmpList[i].menu)
                        tmpMenuList = [].concat(tmpMenuList,tmpList[i].menu)
                }
            }
            columns.unshift({
                    id:'id',                                                  //..菜单id
                    text: '权限菜单(+ / -)',
                    index:'index',                                               //..人员索引
                    value: 'menu_name',
                    haspower:'haspower',
                    width: 300
            })
            that.columns = [].concat(columns)
        },

        /* 重置当前人员权限 */
//         resetUserMenu(){
//             const that = this
//             let tmpList = that.changeData
            
//             const len = tmpList.length
            
//             let currUserIndex = null

//             for(let i = 0;i < len;i++){                                                 //  获取当前人员索引
//                 if(tmpList[i].userId === parseInt(that.userId)){
//                     currUserIndex = i
//                     break
//                 }
//             }

//             tmpList[currUserIndex].menu = [].concat(that.rawData.menu)
//             tmpList[currUserIndex].menuIds = [].concat(that.rawData.menuIds)
//             that.menuIds = [].concat(that.rawData.menuIds)
//             that.changeData = [].concat(tmpList)
//             this.formatDataByTableRule()
//         },
        /* 拷贝某人菜单权限 */
        copyMenuPower(column, event){
                const that = this
              /* 一键展开 */
              if(column.label === '权限菜单(+ / -)'){
                  that.expandedAllMenu();
                  return
              }
              
            /* 拷贝人员权限 */
            const currUserId = that.userId
            let tmpList = that.changeData
            let len = tmpList.length
            let copyUserIndex = column.index                                    //  获取拷贝人员索引
            let currUserIndex = null                                                    //  当前人员索引

let oldExpandStatusArr = []
            for(let i = 0;i < len;i++){                                                 //  获取当前人员索引
                if(tmpList[i].userId === parseInt(currUserId)){
                    currUserIndex = i
                    break
                }
            }

            if(currUserIndex === copyUserIndex){                                        //  如果当前用户自己拷贝自己，则禁止拷贝
                return
            }
            tmpList[currUserIndex].menu = [].concat(tmpList[copyUserIndex].menu)
            // tmpList[currUserIndex].menuIds = [].concat(tmpList[copyUserIndex].menuIds)
            that.changeData = [].concat(tmpList)

            this.isChange = true

             // 保存菜单当前展开状态
            for(let item of this.formatData){
                oldExpandStatusArr.push(item._expanded)
            }
            this.oldExpandStatusArr = [].concat(oldExpandStatusArr)

            this.powerList = [].concat(tmpList[copyUserIndex].menu)

            that.formatDataByTableRule()                                                                    //  格式化数据
        },
//         copyMenuPower(column, event){
//                 const that = this
//               /* 一键展开 */
//               if(column.label === '权限菜单(+ / -)'){
//                   that.expandedAllMenu();
//                   return
//               }
              
//             /* 拷贝人员权限 */
//             const currUserId = that.userId
//             let tmpList = that.changeData
//             let len = tmpList.length
//             let copyUserIndex = column.index                                    //  获取拷贝人员索引
//             let currUserIndex = null                                                    //  当前人员索引
//             for(let i = 0;i < len;i++){                                                 //  获取当前人员索引
//                 if(tmpList[i].userId === parseInt(currUserId)){
//                     currUserIndex = i
//                     break
//                 }
//             }

//             if(currUserIndex === copyUserIndex){                                        //  如果当前用户自己拷贝自己，则禁止拷贝
//                 return
//             }
// console.log('tmpList = ',tmpList)
//             tmpList[currUserIndex].menu = [].concat(tmpList[copyUserIndex].menu)
//             // tmpList[currUserIndex].menuIds = [].concat(tmpList[copyUserIndex].menuIds)
//             that.changeData = [].concat(tmpList)

//             this.isChange = true
//             that.formatDataByTableRule()                                                                    //  格式化数据


//         },
        /* 查询所有人员权限菜单树 */
        queryMenuTreeAllUsers(id){
            const that = this
            let allUserIds = that.allUserIds
            let data = {
                id
            }
             
            _g.showLoading('权限加载中')
            // that.apiPost("admin/users/queryMenuTreeByUserId",data).then(res => {
            that.apiPost("admin/users/queryMenuTreeAllUsers",data).then(res => {
                _g.showLoading().close()
                if(typeof res === 'string'){
                      res = JSON.parse(res)
                    }
                    if ((res.code || res.code === 0)  && res.code != 200) {
                      this.handleError(res)
                    } else if(res.data.isSuccess === 0){                                                            //  成功
                        that.changeData = [].concat(res.data.users)
                        
                        for(let item of res.data.users){
                            allUserIds.push(item.userId)
                        }
                        

                        that.formatDataByTableRule()
                        
                    }else if(res.data.isSuccess === 1){
                        _g.toastMsg("error", res.message)
                    }
            })
        },

        /* 获取所有用户 */
        // getAllUsers(){
        //     const that = this
        //     _g.showLoading('用户加载中')
        //     that.apiPost("admin/users/getAllUsers").then(res => {
        //         _g.showLoading().close()
        //         if(typeof res === 'string'){
        //               res = JSON.parse(res)
        //             }
        //             if ((res.code || res.code === 0)  && res.code != 200) {
        //               this.handleError(res)
        //             } else if(res.data.isSuccess === 0){                                                            //  成功
        //                 if(res.data.userList.length <= 0){
        //                     _g.toastMsg("warning", '暂无用户数据')
        //                 }else{
        //                     that.userList = res.data.userList
        //                 }
        //             }else if(res.data.isSuccess === 1){
        //                 _g.toastMsg("error", res.message)
        //             }
        //     })
        // },
        /* 重置权限 */
        // resetUserMenu(){
        //      if(!this.isChange){
        //         _g.toastMsg('warning','未做任何改变，无需重置权限')
        //         return
        //     }
        //     this.queryMenuTreeAllUsers()
        //     this.isChange = false
        // },
        /* 修改权限 */
        changeUserMenu(){
            const that = this
            let menuIds = []                                                //  拥有的菜单权限集合
            let noMenuIds = []                                          //  没有权限的菜单集合
            let formatData = that.formatData
            const id = that.userId
            let allUserIds = that.allUserIds



            for(let item of formatData){
                if(item.haspower){                      //  如果有该权限菜单
                    menuIds.push(item.id)
                }else{
                    noMenuIds.push(item.id)
                }
            }

            let data = {
                id,
                menuIds
            }

            if(!that.isChange){
                _g.toastMsg('warning','未做任何改变')
                return
            }

            that.$confirm('是否确认修改权限?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning',
                  center: true
              }).then(() => {
                    _g.showLoading('提交中')
                    that.apiPost('admin/users/changeUserMenu',data).then((res) => {
                            _g.showLoading().close()
                            if(typeof res === 'string'){
                                res = JSON.parse(res)
                            }
                            if ((res.code || res.code === 0)  && res.code != 200) {
                                that.handleError(res)
                            } else {
                            if(res.data.isSuccess === 0){             //  成功
                                _g.toastMsg("success", res.message)
                                // that.queryMenuTreeAllUsers()
                                // that.isChange = false
                                
                                // that.changeData = [].concat(res.data.users)
                                // for(let item of res.data.users){
                                //     allUserIds.push(item.userId)
                                // }

                                // that.formatDataByTableRule()
                                //  前端渲染权限为选中
                                // for(let item of formatData){
                                //         for(let userId of allUserIds){
                                //             item['txt' + userId] = '✕'
                                //         }
                                //     }
                               
                                    for(let item of formatData){
                                        // 有权限
                                         for(let itemId of menuIds){
                                                if(itemId === item.id){
                                                    if(item.haspower){                                  
                                                        item['txt' + id] = '√'
                                                }
                                            }
                                        }
                                        // 有权限
                                         for(let itemId of noMenuIds){
                                                if(itemId === item.id){
                                                    if(!item.haspower){                                  
                                                        item['txt' + id] = '✕'
                                                }
                                            }
                                        }
                                }
                                that.$router.push('/admin/users/list')
                            }else{
                                _g.toastMsg("error", res.message)
                            }
                            }
                        })
                    }).catch(() => {});
        },

        /* 下面为tree-grid */
        showRow: function(row) {
            const show = (row.row.parent ? (row.row.parent._expanded && row.row.parent._show) : true)
            row.row._show = show
            return show ? 'animation:treeTableShow 1s;-webkit-animation:treeTableShow 1s;' : 'display:none;'
            },
        // 切换下级是否展开
        toggleExpanded: function(trIndex) {
            const record = this.formatData[trIndex]

            record._expanded = !record._expanded

        },
        // 图标显示
        iconShow(index, record) {
            return (index === 0 && record.children && record.children.length > 0)
        },
        // 一键展开或收缩全部菜单
        expandedAllMenu: function() {
            let formatData = this.formatData
            const len = formatData.length
            if(this.isMenuExpand){                                                      //  如果菜单被一键展开
                for(let i = 0;i < len;i++){
                    const record = this.formatData[i]
                        record._expanded = false
                        this.formatData[i]._expanded = false
                }
            }else{
                for(let i = 0;i < len;i++){
                    const record = this.formatData[i]
                        record._expanded = true
                        this.formatData[i]._expanded = true
                }
            }
            this.isMenuExpand = !this.isMenuExpand
        },
    },
    created () {
        this.userId = this.$route.params.userId
        this.selUserId = this.$route.params.userId
        this.userName = this.$route.params.userName
        this.staffNum = this.$route.params.staffNum
        this.queryMenuTreeAllUsers()
        // this.getAllUsers()
    },
    mixins: [http]
}
</script>

<style scoped>
.titleBar{
    font-size: 14px;
    color: #ef8200;
    border: 1px dashed rgb(242,181,107);
    background-color: rgb(246,232,215);
    height: 30px;
    line-height: 30px;
    padding-left: 10px;
}
</style>

<style rel="stylesheet/css">
  @keyframes treeTableShow {
      /* tree-grid */
    from {opacity: 0;}
    to {opacity: 1;}
  }
  @-webkit-keyframes treeTableShow {
    from {opacity: 0;}
    to {opacity: 1;}
  }
</style>

<style lang="scss" rel="stylesheet/scss" scoped>
  /* tree-grid */
  $color-blue: #2196F3;
  $space-width: 18px;
  .ms-tree-space {
    position: relative;
    top: 1px;
    display: inline-block;
    font-style: normal;
    font-weight: 400;
    line-height: 1;
    width: $space-width;
    height: 14px;
    &::before {
      content: ""
    }
  }
  .processContainer{
    width: 100%;
    height: 100%;
  }
  table td {
    line-height: 26px;
  }

  .tree-ctrl{
    position: relative;
    cursor: pointer;
    color: $color-blue;
    margin-left: -$space-width;
  }
</style>

